<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport"
    content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>MagicMouse</title>
</head>

<body>
  <h1>Magic Mouse</h1>
  WebSocket Status: <span id="wsstatus"></span><br />
  Alpha: <span id="alpha"></span><br />
  Beta: <span id="beta"></span><br />
  Gamma: <span id="gamma"></span><br />
  <script>
    function throttle(method, delay, duration) {
      var timer = null,
        begin = new Date();
      return function () {
        var context = this,
          args = arguments,
          current = new Date();;
        clearTimeout(timer);
        if (current - begin >= duration) {
          method.apply(context, args);
          begin = current;
        } else {
          timer = setTimeout(function () {
            method.apply(context, args);
          }, delay);
        }
      }
    }
    function showStatus(content) {
      var status = document.getElementById("wsstatus");
      status.innerHTML = content;
      console.log("status", content)
    }
    function showError(content) {
      var status = document.getElementById("wsstatus");
      status.innerHTML = content;
      console.error("error", content)
    }
    var apiUrl = 'ws://' + window.location.host + ':14514/api/v1/ws';
    var ws = new WebSocket(apiUrl);
    try {
      ws.onopen = function () {
        showStatus('Success');
      };
      ws.onclose = function () {
        if (ws) {
          ws.close();
          ws = null;
        }
        showStatus('Closed');
      };
      ws.onerror = function () {
        if (ws) {
          ws.close();
          ws = null;
        }
        showError('Error');
      };
    } catch (e) {
      alert(e.message);
    }
    if (window.DeviceOrientationEvent) {
      window.addEventListener('deviceorientation', throttle(function (event) {
        var a = document.getElementById('alpha'),
          b = document.getElementById('beta'),
          g = document.getElementById('gamma'),
          alpha = event.alpha,
          beta = event.beta,
          gamma = event.gamma;

        a.innerHTML = Math.round(alpha);
        b.innerHTML = Math.round(beta);
        g.innerHTML = Math.round(gamma);

        var backJson = {
          'cmd': 'data_angle_frame',
          'data': {
            'alpha': alpha,
            'beta': beta,
            'gamma': gamma,
          }
        };
        ws.send(JSON.stringify(backJson));
        console.log("sent", backJson);

      }, 20, 35), false);
    } else {
      document.querySelector('body').innerHTML = 'No supported sensors detected!';
    }
  </script>
</body>

</html>